
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.location.*;
import javax.microedition.io.*;
import java.io.*;
//import Base64Encoder;
//import URLEncoder;
//import com.mot.iden.device.*;
//import com.mot.iden.customercare.*;

public class udgpsm extends MIDlet implements CommandListener, LocationListener {
    private Display display;
    private Form form;
    private Command cmdClose = new Command("Close", Command.EXIT, 1);
    
    private LocationProvider locationProvider = null;
    private int dispcount = 0;
    private int lpupcount = 0;

    public udgpsm(){
        
        // *****************************************************************
        // User
        // Defined
        // Global
        // Positioning
        // System
        // Midlet
        // *****************************************************************
        
    }    
    
    public void startApp() {
        display = Display.getDisplay(this);

        if (form == null) {
            form = new Form("UDGPSM");
            display.setCurrent(form);
        }
        //form.setFullScreenMode(true);
        form.addCommand(cmdClose);
        form.setCommandListener(this);
        /*
        form.append( "hello world\n" );
        form.append( "hello " + Base64Encoder.base64Encode( " world?!@#&".getBytes() ) );
        form.append( "hello " + URLEncoder.URLencode( " world?!@#&" ) );
        */

        // locationProvider gets the GPS data
        if (locationProvider == null) {
            createLocationProvider();

            // this handles the GPS data provided by the LocationProvider
            Thread locationThread = new Thread() {
                public void run(){
                    createLocationListener();
                }
            };

            locationThread.start();
        }
    }

    public void pauseApp() {}

    public void destroyApp(boolean unconditional) {
    }
    
    public void commandAction(Command command, Displayable displayable) {
    	if (command == cmdClose) {
        destroyApp(false);
        notifyDestroyed();
    	}
    }




    public void displayMessage(String s) {
        Alert a = new Alert("", s, null, null);
        a.setTimeout(Alert.FOREVER);
        display.setCurrent(a, form);
    }  

    // sets up our GPS data provider
    private void createLocationProvider() {
        Criteria cr = new Criteria();
        //cr.setHorizontalAccuracy(NO_REQUIREMENT); //in meters
        //cr.setVerticalAccuracy(NO_REQUIREMENT); //in meters
        //cr.setPreferredResponseTime(NO_REQUIREMENT); //in milliseconds
        //cr.setPreferredPowerConsumption(NO_REQUIREMENT); //NO_REQUIREMENT, POWER_USAGE_LOW, POWER_USAGE_MEDIUM, POWER_USAGE_HIGH
        //cr.setCostAllowed(true); //true false
        cr.setSpeedAndCourseRequired(true); //true false
        cr.setAltitudeRequired(true); //true false
        //cr.setAddressInfoRequired(false); //true false

        try {
            locationProvider = LocationProvider.getInstance(cr);
        } catch (Exception e) {
           form.append("createLocationProvider: " + e.getMessage());
        }
    }
    
    private void createLocationListener(){
          try {
            // the 2nd value is time interval in seconds
            // the 3rd value is timeout in seconds
            // the 4th value is max age in seconds
            locationProvider.setLocationListener(this, 1, -1, -1); 
          } catch (Exception e) {
           form.append("createLocationListener: " + e.getMessage());
        } 
   }
  
    // one of the required methods of the LocationListener interface   
    // this is where we get a new location from the locationProvider
    public void locationUpdated(final LocationProvider provider, final Location location) {
        try {
          Thread getLocationThread = new Thread(){
              public void run(){
                 getLocation(provider, location);
              }
          };
          
          getLocationThread.start();
        } catch (Exception e) {
          form.append("locationUpdated: " + e.getMessage());
        } 
    }    
 
        // one of the required methods of the LocationListener interface, not used by us
    public void providerStateChanged(LocationProvider provider, int newState) {
      lpupcount++;
    }
    
    private void getLocation(LocationProvider provider, Location location){
        try {
           //  Uncomment the if statement below if you only want satellite data
           //  327681 = 0x00050001 = MTE_SATELLITE | MTY_TERMINALBASED | MTA_ASSISTED
           //  8 = 0x00000008 = MTE_CELLID
           // these values can be obtained by calling location.getLocationMethod()
                         
           // if ((location.getLocationMethod() & Location.MTE_SATELLITE) !=0) {

                String               extraInfo_nmea       = location.getExtraInfo("application/X-jsr179-location-nmea");
/*
                String               extraInfo_lif        = location.getExtraInfo("application/X-jsr179-location-lif");
                String               extraInfo_text       = location.getExtraInfo("text/plain");
                int                  locationMethod       = location.getLocationMethod();
                float                speed                = location.getSpeed();
                float                course               = location.getCourse();
                long                 timestamp            = location.getTimestamp();
                boolean              valid                = location.isValid();

                QualifiedCoordinates qualifiedCoordinates = location.getQualifiedCoordinates();
                double               lat                  = qualifiedCoordinates.getLatitude();
                double               lon                  = qualifiedCoordinates.getLongitude();
                double               alt                  = qualifiedCoordinates.getAltitude();
                double               horzAcc              = qualifiedCoordinates.getHorizontalAccuracy();
                double               vertAcc              = qualifiedCoordinates.getVerticalAccuracy();

                AddressInfo          addressInfo          = location.getAddressInfo();
                int                  batlvl               = StatusManager.getStatus(StatusManager.BATTERY_LEVEL);
                int                  sinlvl               = StatusManager.getStatus(StatusManager.SIGNAL_STRENGTH);
*/

                form.deleteAll();
                form.append("dispcount=" + String.valueOf(dispcount++) + "\n");
                form.append("lpupcount=" + String.valueOf(lpupcount) + "\n");
                //form.append("ein=" + String.valueOf(extraInfo_nmea) + "\n");

                int pos = 0;
                int next;
                while ((next = extraInfo_nmea.indexOf('$', pos + 1)) >= 0) {
                  form.append(extraInfo_nmea.substring(pos, next) + "\n");
                  pos = next;
                }
                form.append(extraInfo_nmea.substring(pos) + "\n");    

/*                    
                if (qualifiedCoordinates != null){

                    // beep when we get a fix, you can comment this out if you want
                    //AlertType.WARNING.playSound(display); 
                    if (!Float.isNaN(location.getSpeed())) {
                        speed = location.getSpeed();
                    }

                    String postString = "lat=" + String.valueOf(qualifiedCoordinates.getLatitude()) 
                            + "&lng=" + String.valueOf(qualifiedCoordinates.getLongitude())
                            + "&mph=" + String.valueOf((int)(speed/1609*3600))
                            + "&dir=" + String.valueOf(azimuth) 
                            + "&mi=" + String.valueOf((int)(distance/1609))
                            + "&dt=" + d.toString()
                            + "&lm=" + location.getLocationMethod();

                    form.append("eil=" + String.valueOf(extraInfo_lif) + "\n");
                    form.append("eit=" + String.valueOf(extraInfo_text) + "\n");
                    form.append("lme=" + String.valueOf(locationMethod) + "\n");
                    form.append("speed=" + String.valueOf(speed) + "\n");
                    form.append("course=" + String.valueOf(course) + "\n");
                    form.append("timestamp=" + String.valueOf(timestamp) + "\n");
                    form.append("valid=" + String.valueOf(valid) + "\n");
                    form.append("lat=" + String.valueOf(lat) + "\n");
                    form.append("lng=" + String.valueOf(lon) + "\n");
                    form.append("alt=" + String.valueOf(alt) + "\n");
                    form.append("horzAcc=" + String.valueOf(horzAcc) + "\n");
                    form.append("vertAcc=" + String.valueOf(vertAcc) + "\n");
                }
*/
            //} // this ends the satellite if block which is currently commented out above
        } catch (Exception e) {
            form.append("getLocation: " + e.getMessage());
        }
    }
}


